<template>
  <view class="container">
    <view class="tip ">
      <image v-if="approval_status==2" src="~@/static/images/approval/agree.png"  class="approvalimg"></image>
      <image  v-else-if="approval_status==3" src="~@/static/images/approval/reject.png"   class="approvalimg"></image>
    </view>
    <view class="tui-order-header">
      <view class="tui-text">
        采购编号：
        <text class="tui-bold">{{ BuyListInfo.billPurchaseNu }}</text>
      </view>
      <view class="tui-text">
        申请发起人：
        <text class="tui-bold">
          {{
          BuyListInfo.createBy
          }}
        </text>
      </view>
      <view class="tui-text">
        备注：
        <text class="tui-bold">{{ BuyListInfo.remark }}</text>
      </view>
    </view>
    <uni-section v-if="BuyProductList.length" title="采购申请产品清单"></uni-section>
    <template v-for="(item, index) in BuyProductList">
      <tui-list-cell :hover="false" :key="index">
        <view class="tui-line-cell">
          <view class="tui-title">{{ item.materialName }}</view>
          <view class="tui-right">
            数量：
            <text class="text-bold">{{ item.quantity }}</text>
          </view>
        </view>
      </tui-list-cell>
    </template>
    <view class="tui-order-tracking" :class="{'mbot':approval_btn_isshow}">
      <tui-time-axis>
        <template v-for="(item, index) in historyFlow">
          <view :key="index" v-if="item.actType == 'userTask'">
            <tui-timeaxis-item bgcolor="none">
              <template v-slot:node>
                <view
                  class="tui-node"
                  :class="{
                    'tui-bg-primary': item.taskState == 'finish' &&
                      index == 1 &&
                      historyFlow[0].actType=='endEvent' ||!historyFlow[0].endTime && index==0
                  }"
                >
                  <tui-icon
                    v-if="item.taskState == 'finish' && index == 1 &&historyFlow[0].actType=='endEvent'"
                    name="check"
                    color="#fff"
                    :size="14"
                  ></tui-icon>
                  <text v-else-if="item.taskState == 'todo'" class="goods-manage-icon icon">&#xe60c;</text>
                  <text
                    v-else-if="item.taskState == 'finish'"
                    class="goods-manage-icon icon"
                  >&#xe679;</text>
                  <text v-else class="goods-manage-icon icon"></text>
                </view>
              </template>

              <template v-slot:content>
                <view>
                  <view v-if="item.taskState == 'todo'">
                    <view class="tui-order-title">审批中</view>
                    <view class="tui-order-desc">{{ item.actName }}</view>
                  </view>
                  <view
                    v-else-if="
                      item.taskState == 'finish' &&
                      index == 1 &&
                      historyFlow[0].actType=='endEvent'
                    "
                  >
                    <view
                      class="tui-order-title"
                    >{{getText(item)}}</view>
                    <view
                      class="tui-order-desc"
                    >{{ item.comment&& item.comment!='null'?item.actName+"【" + item.comment + "】" :item.actName }}</view>
                  </view>
                  <view v-else>
                    <view
                      class="tui-order-title tui-gray"
                    >{{getText(item)}}</view>
                    <view class="tui-order-desc tui-light-gray">
                      {{
                       item.comment&& item.comment!='null'?item.actName+"【" + item.comment + "】" :item.actName
                      }}
                    </view>
                  </view>

                  <view class="tui-order-time tui-gray">
                    {{
                    item.endTime | dateFormat
                    }}
                  </view>
                </view>
              </template>
            </tui-timeaxis-item>
          </view>
        </template>
      </tui-time-axis>
    </view>
    <view class="btnbox flex" v-if="approval_btn_isshow">
      <view
        v-for="(item,index) in opts.description.buttonInfo"
        :key="index"
        class="item"
        :class="[item.varValue=='agree'?'tui-light-green':'tui-light-brownish']"
        :hover-class="item.varValue=='agree'?'button-green-hover':'button-brownish-hover'"
        @click="showModal(index)"
      >{{item.buttonName}}</view>

     </view>
    <tui-modal :show="modelIsShow" @cancel="modelIsShow=false" :custom="true">
      <view class="tui-modal-custom">
        <view class="tui-prompt-title">审批意见</view>
        <view v-if="opts.description !='description.appointUser'">
          <kmlc-form-select-user label="审批人员" select-type="single" v-model="selectPersionData"></kmlc-form-select-user>
        </view>
        <tui-list-cell :hover="false">
          <view class="tui-title">审批意见</view>
          <view class="tui-input">
            <textarea
              auto-height
              style="max-width:350upx;"
              v-model="approval_msg"
              placeholder="备注信息"
            />
          </view>
        </tui-list-cell>

        <tui-button class="subtn tui-modal-btn" type="primary" @click="handleClick">立即提交</tui-button>
      </view>
    </tui-modal>
   
    <tui-modal :show="modal2isshow" @cancel="modal2isshow=!modal2isshow" :custom="true">
      <view class="tui-modal-custom">
        <view class="tui-prompt-title">审批意见</view>
        
        <tui-list-cell :hover="false">
          <view class="tui-title">驳回原因</view>
          <view class="tui-input">
            <textarea
              auto-height
              style="max-width:350upx;"
              v-model="approval_msg"
              placeholder="填写原因"
            />
          </view>
        </tui-list-cell>
        <tui-button class="subtn tui-modal-btn" type="primary" @click="handleClick2">立即提交</tui-button>
      </view>
    </tui-modal>

    <tui-tips ref="toast"></tui-tips>

  </view>
</template>

<script>
import {
  getBuyListInfoById,
  getBuyProductList,
  gethistoryFlow,
  submitTask,
  getTaskInfo
} from "@/pages/work/interface.js";
export default {
  components: {},
  onLoad(options) {
    let that = this;
    console.log('options.description:',options.description);
    options.description = decodeURIComponent(options.description);
    // console.log('temp:',temp);
    
      options.description =typeof options.description == "string" && options.description.indexOf("{") > -1 
      &&JSON.parse(options.description);
      console.log('options.description:',options.description);
      
    
    
   
    this.opts = options;
    this.approval_btn_isshow =
      this.opts.assignee && this.opts.assignee == this.userInfo.userName
        ? true
        : false;

    Promise.all([
      that.getBuyListInfoByIds(),
      that.getBuyProductLists(),
      that.gethistoryFlows()
    ]);
  },
  data() {
    return {
      opts: {},
      BuyListInfo: {},
      BuyProductList: [],
      historyFlow: [],
      defaultTypes: {
        startEvent: "发起事件",
        userTask: "审批通过"
      },
      modelIsShow: false,
      modal2isshow: false,
      approval_msg: "",
      selectPersionData: [],//选择的人
      modalIndex: 0, //点击的第几个审批按钮
      approval_btn_isshow: false, //审批按钮是否显示
      approval_status:0,
      showResultImgIndex:0,//显示审批图片index,
      ResultImgList:[],
      approval_count:0,
    };
  },
  mounted() {
    // console.log(this.userInfo);
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo;
    }
  },
  methods: {
    //获取采购详情
    async getBuyListInfoByIds(isLoadMore) {
      let params = {
        id: this.opts.approvalId
      };
      console.log("params:", params);
      let Res = await getBuyListInfoById(params);
      console.log(Res);
      if (Res && Res.success) {
        this.BuyListInfo = Res.result;
        // 流程状态(1.审批中 2.已完成 3.驳回)
        this.approval_status = Res.result.processStatus;
      } else {
        uni.showToast({
          icon: "none",
          title: Res.message || "获取失败~！"
        });
      }
    },
    //获取采购商品列表
    async getBuyProductLists() {
      let params = {
        id: this.opts.approvalId
      };
      console.log("params:", params);
      let Res = await getBuyProductList(params);
      console.log(Res);
      if (Res && Res.success) {
        this.BuyProductList = Res.result;
      } else {
        uni.showToast({
          icon: "none",
          title: Res.message || "获取失败~！"
        });
      }
    },
    //获取已执行流程
    async gethistoryFlows() {
      let params = {
        procInsId: this.opts.procInsId,
        tenantId: "kmlc"
      };
      console.log("params:", params);
      let Res = await gethistoryFlow(params);
      console.log(Res);
      if (Res && Res.success) {
        this.historyFlow = Array.isArray(Res.result) && Res.result.reverse();

        let temp =
          this.historyFlow[0] && this.historyFlow[0].actType == "endEvent"
            ? ""
            : this.historyFlow[0] && this.historyFlow[0].assignee;
        this.approval_btn_isshow = temp == this.opts.assignee ? true : false;

        // 审批人是自己，而且已经提交过审批，才执行
        this.approval_btn_isshow &&this.approval_count&& this.getTaskInfos();

        //是否显示审批结果图片
        this.showResultImg();
      } else {
        uni.showToast({
          icon: "none",
          title: Res.message || "获取失败~！"
        });
      }
    },
    //提交执行信息
    async submitTasks() {
      let modalBtn =
        this.opts.description.buttonInfo &&
        this.opts.description.buttonInfo[this.modalIndex];
      console.log(modalBtn);
      let subData = this.historyFlow[this.historyFlow.length - 1];
      let params = {
        taskId: this.opts.taskId,
        comment: this.approval_msg,
        procInsId: subData.procInsId,
        assigneeName: this.userInfo.userRealName,
        businessKey: this.opts.approvalId,
        assignee: this.selectPersionData.length&&this.selectPersionData[0].value,
        varKey: modalBtn.varKey,
        varValue: modalBtn.varValue,
        buttonName: modalBtn.buttonName
      };
      // console.log("params:", params);
      let Res = await submitTask(params);
      this.approval_count++;
      // 清除选的人和意见
        this.selectPersionData = [];
        this.approval_msg = '';
      if (Res && Res.success) {
        this.gethistoryFlows();
        this.getBuyListInfoByIds();
      } else {
        uni.showToast({
          icon: "none",
          title: Res.message || "获取失败~！"
        });
      }
    },
    //获取待执行详情（主要是按钮）
    async getTaskInfos() {
      let params = {
        procInsId: this.opts.procInsId,
        tenantId: "kmlc"
      };
      console.log("params:", params);
      let Res = await getTaskInfo(params);
      console.log(Res);
      if (Res && Res.success) {
        let temp =
          Res.result.description && typeof Res.result.description == "string" &&
          Res.result.description.indexOf("{") > -1 &&
          JSON.parse(Res.result.description);
          this.opts['description']['buttonInfo'] = temp && temp.buttonInfo;
          this.opts['taskId'] = Res.result.taskId;
          
      } else {
        uni.showToast({
          icon: "none",
          title: Res.message || "获取失败~！"
        });
      }
    },
    //显示modal
    showModal(index) {
      this.modalIndex = index;
      if (index) {
        this.modal2isshow = !this.modal2isshow;
      } else {
        this.modelIsShow = !this.modelIsShow;
      }
    },
    //同意modal 确认按钮事件
    handleClick() {
      if (
        !this.selectPersionData.length &&
        this.opts.description != "useRecive"
      ) {
        this.showTips({ msg: "请选择下一步审批人员！", type: "danger" });
        return;
      }
      this.modelIsShow = !this.modelIsShow;
      this.submitTasks();
    },
    //驳回modal 确认按钮事件
    handleClick2(e) {
      this.modal2isshow = !this.modal2isshow;
      console.log(e);
      // 驳回
      this.submitTasks();
    },
    //显示顶部提示栏
    showTips(opt) {
      this.$refs.toast.showTips(opt);
    },
    //字符串拼接
    getText(data) {
      let temp = "";
      
      if (data.varsLocal.assigneeName) {
        temp +=  data.varsLocal.assigneeName;
      }
      if (data.varsLocal.buttonName) {
        temp += "（已" + data.varsLocal.buttonName+"）";
      }
      
      return temp;
    },
    //显示审批结果
    showResultImg(){
      /*
      0:不显示，1：审批驳回，2：审批通过
      */
      this.showResultImgIndex = this.historyFlow.length &&this.historyFlow[0].actType == "endEvent" &&this.historyFlow.map(item=>{
        return item.varsLocal&& item.varsLocal!='null' &&item.varsLocal.buttonName&&item.varsLocal.buttonName=="驳回"?1:2;
      })||0;

    }
  }
};
</script>

<style lang="scss">
.tui-order-header {
  padding: 30upx;
  box-sizing: border-box;
  background: #fff;
}

.tui-text {
  font-size: 28upx;
  color: #333;
  padding: 4upx;
}

.tui-bold {
  font-weight: bold;
}

.tui-node {
  background: #ddd;
  height: 44upx;
  width: 44upx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  padding-top: 0;
}

.tui-node-small {
  height: 16upx !important;
  width: 16upx !important;
}

.tui-bg-primary {
  background: #5677fc !important;
}

.tui-order-tracking {
  padding: 30upx 30upx 30upx 40upx;
  background: #fff;
  margin-top: 20upx;
  box-sizing: border-box;
}

.tui-order-title {
  color: #333;
  font-weight: bold;
  font-size: 32upx;
  font-family: "microsoft yahei";
}

.tui-order-desc {
  font-size: 28upx;
  color: #333;
  padding: 12upx 0;
}

.tui-ptop {
  display: flex;
  justify-content: flex-start;
  line-height: 28upx;
}

.tui-order-time {
  font-size: 24upx;
  font-weight: bold;
}

.tui-gray {
  color: #848484 !important;
  background: #fff;
}

.tui-light-gray {
  color: #888 !important;
}

.tui-line-cell {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.tui-title {
  min-width: 100upx;
  line-height: 32rpx;
  flex-shrink: 0;
}
.tui-right {
  margin-left: auto;
  margin-right: 34upx;
  font-size: 26upx;
  line-height: 1;
  color: #333;
}
.text-bold {
  font-weight: bold;
}
.flex {
  display: flex;
  .item {
    flex: 1;
  }
}
.btnbox {
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  box-shadow: 6px 2px 12px 0 rgba(0, 0, 0, 0.2);
  width: 100%;
  text-align: center;
  z-index: 999;
  .item {
    padding: 20upx 0;
    font-size: 34upx;
    cursor: pointer;
  }
  .button-green-hover {
    background: darken(#e8f6e8, 10%);
    color: darken(#44cf85, 10%) !important;
  }
  .button-brownish-hover {
    background: darken(#fcebef, 10%);
    color: darken(#8a5966, 10%) !important;
  }
}
.tui-title {
  font-size: 32rpx;
}
.tui-input {
  font-size: 32rpx;
  color: #333;
  padding-left: 20rpx;
  flex: 1;
  text-align: left;
}
.tui-modal-custom {
  text-align: center;
}
.subtn {
  margin-top: 40upx;
  width: 46%;
  height: 32px;
  line-height: 32px;
  position: relative;
  border-radius: 4px;
  font-size: 11px;
  overflow: visible;
  margin-left: 0;
  margin-right: 0;
}
.tui-prompt-title {
  text-align: center;
  font-size: 16px;
  color: #333;
  padding-top: 9px;
  font-weight: bold;
}
.mbot {
  margin-bottom: 100upx;
}
.tip{
  width: 150upx;
  height: 130upx;
  position:absolute;
  top: 40upx;
  right: 40upx;
  .approvalimg{
    width: 100%;
    height: 100%;
    z-index: 999;
    opacity: 0;
     animation: yourAnimation .4s ease-in .1s  1 forwards;
  }
  
    
}

@keyframes yourAnimation{
    0%{
      opacity: 0;
      transform: rotate(0) scale(2) translateX(0) translateY(0) skewX(0) skewY(0);
      filter: blur(5px);
        }
    23%{
        transform: rotate(0) scale(1.5) translateX(0) translateY(0) skewX(0) skewY(0);
        filter: blur(1px);
        opacity: 0.5;
        }
         100%{
        transform: rotate(0) scale(1) translateX(0) translateY(0) skewX(0) skewY(0);
        opacity: 1;
        }
}


</style>
